<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-button type="primary" class="divMia" @click="newly"
        >新增分店</el-button
      >
    </div>
    <div class="text item">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        max-height="600"
      >
        <el-table-column
          label="序号"
          align="center"
          type="index"
          :index="indexMethod"
          width="80"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          align="center"
          label="店铺名称"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="addesss"
          show-overflow-tooltip
          align="center"
          label="店铺地址"
          width="180"
        >
        </el-table-column>
        <el-table-column prop="regions" align="center" label="地区" width="180">
        </el-table-column>
        <el-table-column
          prop="account_by_seller_shop.seller_name"
          align="center"
          label="账号"
        >
        </el-table-column>
        <el-table-column prop="address" align="center" label="角色">
        </el-table-column>
        <el-table-column prop="manager_name" align="center" label="负责人">
        </el-table-column>
        <el-table-column prop="manager_phone" align="center" label="负责人电话">
        </el-table-column>
        <el-table-column prop="status_text" align="center" label="地铺状态">
        </el-table-column>
        <el-table-column prop="address" align="center" label="操作" width="220">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status == 0"
              size="mini"
              type="primary"
              @click="enable(scope.row)"
              >启用</el-button
            >
            <el-button
              v-else
              size="mini"
              type="danger"
              @click="blockUp(scope.row)"
              >停用</el-button
            >
            <el-button
              size="mini"
              type="warning"
              @click="handleDelete(scope.row)"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" @click="sanChu(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[100, 200, 300, 400]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <span>
        <el-form ref="form" :model="form" label-width="90px">
          <div class="divWidth">
            <el-form-item label="账号">
              <el-input v-model="form.seller_name"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="form.password"></el-input>
            </el-form-item>
            <el-form-item label="绑定角色">
              <el-select
                v-model="form.reg"
                placeholder="请选择绑定角色"
                style="width: 100%"
              >
                <el-option label="区域一" value="shanghai"></el-option>
                <el-option label="区域二" value="beijing"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="地区">
              <el-cascader
                v-model="form.region"
                :options="options"
                :props="cascaderprops"
                style="width: 100%"
                @change="cascaderChange"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="店铺名称">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="店铺地址">
              <el-input v-model="form.addesss"></el-input>
            </el-form-item>
            <el-form-item label="店铺电话">
              <el-input v-model="form.telephone"></el-input>
            </el-form-item>
            <el-form-item label="负责人姓名">
              <el-input v-model="form.manager_name"></el-input>
            </el-form-item>
            <el-form-item label="负责人电话">
              <el-input v-model="form.manager_phone"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="商品图片">
            <el-upload
              class="upload-demo"
              action
              :http-request="uploadFiles"
              ref="upload"
              :limit="fileLimit"
              :on-remove="handleRemove"
              :file-list="fileList"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :headers="headers"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过5M
              </div>
            </el-upload>
            <el-image
              v-for="(item, index) in imgShowList"
              :key="index"
              class="imageGood"
              :src="item"
              style="width: 180px; height: 120px"
            ></el-image>
          </el-form-item>
          <el-form-item label="店铺详情">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="form.details"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="adding">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  uploadFiles,
  storeList,
  addShop,
  region,
  storeStatus,
  shopDetails,
  StoreDeletion,
} from "../../../../utils/api.js";
export default {
  data() {
    return {
      cascaderprops: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          console.log(node, resolve);
          const { value, level } = node;
          let nodeList = [];
          setTimeout(() => {
            this.regions2(value).then((res) => {
              if (res.data.status) {
                if (node.level == 1) {
                  this.options.find((e) => {
                    return e.id == value;
                  }).children = res.data;
                  this.cityList = [];
                  this.cityList.push(
                    this.options.findIndex((e) => {
                      return e.id == value;
                    })
                  );
                  this.options.forEach((item) => {
                    if (item.children) {
                      item.children.forEach((item1) => {
                        item1.label = item1.name;
                        item1.value = item1.id;
                      });
                    }
                  });
                  nodeList = this.options.find((e) => {
                    return e.id == value;
                  }).children;
                } else if (node.level == 2) {
                  this.options[this.cityList[0]].children.find((e) => {
                    return e.id == value;
                  });
                  this.options[this.cityList[0]].children.find((e) => {
                    return e.id == value;
                  }).children = res.data;
                  this.options[this.cityList[0]].children
                    .find((e) => {
                      return e.id == value;
                    })
                    .children.forEach((item) => {
                      item.label = item.name;
                      item.value = item.id;
                      item.leaf = item.depth;
                    });
                  nodeList = this.options[this.cityList[0]].children.find(
                    (e) => {
                      return e.id == value;
                    }
                  ).children;
                  console.log(nodeList);
                }
              }
              resolve(nodeList);
            });
          }, 1000);
        },
      },
      loading: false,
      token: sessionStorage.getItem("token"),
      dialogVisible: false,
      imgHeader: this.Global.imgHeader,

      cityList: [],
      dataList: {
        name: "",
        area: "",
        addesss: "",
        manager_name: "",
        manager_phone: "",
      },
      tableData: [],
      //收集数据
      form: {
        id: "",
        name: "",
        region: "",
        province: "",
        city: "",
        area: "",
        addesss: "",
        seller_name: "",
        password: "",
        manager_name: "",
        manager_phone: "",
        seller_id: "",
        telephone: "",
        details: "",
        img: "",
      },
      //当前页数
      page: 1,
      limit: 10,
      total: 0,
      //地区
      options: [],
      //上传
      fileList: [],
      fileType: ["png", "jpg", "jpeg"],
      fileLimit: 8,
      headers: { "Content-Type": "multipart/form-data" },
      imgShowList: [],
      imgShowForm: [],
      parent_id: 0,
    };
  },
  methods: {
    cascaderChange(e) {
      if (e) {
        this.form.province = e[0];
        this.form.city = e[1];
        this.form.area = e[2];
      }
    },
    //启用
    enable(row) {
      this.loading = true;
      storeStatus(this.token, row.id).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "修改成功",
            type: "success",
            onClose: (res) => {},
          });
          this.loading = false;
          this.storeLists();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //编辑
    handleDelete(row) {
      this.loading = true;
      shopDetails(this.token, row.id)
        .then((res) => {
          if (res.data.status) {
            this.form = res.data.data;
            this.form.img = this.form.img.split(",");
            if (res.data.data.account_by_seller_shop) {
              this.form.seller_name =
                res.data.data.account_by_seller_shop.seller_name;
              this.form.password =
                res.data.data.account_by_seller_shop.password;
            }
            // console.log(this.options, 'options');
            this.regions2(res.data.data.province).then((res1) => {
              this.options.find((e) => {
                return e.id == res.data.data.province;
              }).children = res1.data;
              let id = this.options
                .find((e) => {
                  return e.id == res.data.data.province;
                })
                .children.find((e) => {
                  return e.id == res.data.data.city;
                }).id;
              this.regions2(id).then((res2) => {
                this.options
                  .find((e) => {
                    return e.id == res.data.data.province;
                  })
                  .children.find((e) => {
                    return e.id == res.data.data.city;
                  }).children = res2.data;
                let list = [
                  res.data.data.province,
                  res.data.data.city,
                  res.data.data.area,
                ];

                console.log(this.options);
                this.dialogVisible = true;
                setTimeout(() => {
                  this.form.region = list;
                  console.log(list);
                  console.log(222);
                }, 2000);
              });
            });
            // this.options.push(this.form.get_province.label)
            this.form.img.forEach((item) => {
              this.imgShowList.push(this.imgHeader + item);
              this.imgShowForm.push(item);
            });
            // console.log(res.data.data, '=-======');
            // console.log(this.form)
            let timer = setTimeout(() => {
              this.loading = false;
              clearTimeout(timer);
            }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    //停用
    blockUp(row) {
      this.loading = true;
      storeStatus(this.token, row.id).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "修改成功",
            type: "success",
            onClose: (res) => {},
          });
          this.loading = false;
          this.storeLists();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    indexMethod(index) {
      return index + 1;
    },
    //新增分店
    newly() {
      this.dialogVisible = true;
    },
    //关闭
    handleClose(done) {
      (this.imgShowList = []), (this.imgShowForm = []), (this.form = {});
      this.dialogVisible = false;
      this.regions1();
      this.storeLists();
    },
    //删除
    sanChu(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          StoreDeletion(this.token, row.id).then((res) => {
            if (res.data.status) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.storeLists();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //确定添加
    adding() {
      this.form.img = this.imgShowForm.toString();
      this.addShops();
    },
    //页数
    handleSizeChange(val) {
      this.limit = val;
      this.storeLists();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.storeLists();
    },
    //上传
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    handleRemove() {},
    //这是我自定义的移除事件
    handleClosedelete(i) {
      // this.fileList.splice(i, 1);//删除上传的文件
    },
    //上传文件的格式
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    //上传文件的事件
    uploadFiles(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      uploadFiles(item.file).then((res) => {
        if (res.data.status != false || res.data.id != null) {
          console.log(res);
          res.data.data.saveurl; //半截
          res.data.data.weburl; //全拼
          this.imgShowList.push(res.data.data.weburl);
          this.imgShowForm.push(res.data.data.saveurl);
          this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
          let i = this.fileList.indexOf(item.file);
          this.handleSuccess();
        }
      });
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClosedelete();
    },
    //店铺管理
    storeLists() {
      this.loading = true;
      storeList(
        this.token,
        this.dataList.name,
        this.dataList.area,
        this.dataList.addesss,
        this.dataList.manager_name,
        this.dataList.manager_phone,
        this.limit,
        this.page
      )
        .then((res) => {
          if (res.data.status) {
            this.tableData = res.data.data.data;
            this.total = res.data.data.total;
            this.tableData.forEach((item) => {
              if (item.img) {
                item.image = item.img;
                item.img = this.imgHeader + item.img[0];
              }
              if (item.status == 1) {
                item.status_text = "启用";
              }
              if (item.status == 0) {
                item.status_text = "禁用";
              }
              item.regions =
                item.get_province.name +
                "-" +
                item.get_city.name +
                "-" +
                item.get_area.name;
            });
            let timer = setTimeout(() => {
              this.loading = false;
              clearTimeout(timer);
            }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    //添加店铺
    addShops() {
      addShop(
        this.token,
        this.form.name,
        this.form.seller_id,
        this.form.province,
        this.form.city,
        this.form.area,
        this.form.addesss,
        this.form.seller_name,
        this.form.password,
        this.form.manager_name,
        this.form.manager_phone,
        this.form.telephone,
        this.form.img,
        this.form.details
      ).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.form = {};
        } else {
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
            let timer = setTimeout(() => {
              this.$message.error("错误，请刷新");
            }, 5000);
          }
          this.$message.error(res.data.msg);
        }
      });
    },
    regions1() {
      this.loading = true;
      region(this.token, this.parent_id)
        .then((res) => {
          if (res.data.status) {
            this.options = res.data;
            this.options.forEach((item) => {
              item.label = item.name;
              item.value = item.id;
            });
            let timer = setTimeout(() => {
              this.loading = false;
              clearTimeout(timer);
            }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    regions2(id) {
      let promis = new Promise((resolve, reject) => {
        region(this.token, id)
          .then((res) => {
            resolve(res);
            if (res.data.status) {
            } else {
              if (res.data.msg == "token失效,请重新进行登录") {
                this.$router.push("/login");
              }
              if (res.data.msg == "此账号没有权限") {
                this.$message.error(res.data.msg);
                this.loading = false;
              }
              let timer = setTimeout(() => {
                this.$message.error(res.data.msg);
              }, 5000);
            }
          })
          .catch((err) => {
            console.log(err.message);
          });
      });
      return promis;
    },
  },
  mounted() {
    this.storeLists();
    this.regions1();
    this.form.seller_id = this.$route.params.id;
  },
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.clearfix {
  text-align: right;
}

.box-card {
  width: 100%;
}

.imageGood {
  margin: 0 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.divWidth {
  width: 70%;
}
</style>